package avicit.bdp.dcs.utils;

import avicit.bdp.common.utils.database.IotDbSessionUtils;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.iotdb.isession.pool.SessionDataSetWrapper;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.read.common.Field;
import org.apache.iotdb.tsfile.read.common.RowRecord;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class IotdbTest {

    private static String deviceId = "root.liyb.test";

    public static void main(String[] args) {
        try {
            select();

            IotDbSessionUtils.createSessionPool("192.168.0.22", 6667, "root", "root", 50);

            //            IotDbSessionUtils.deleteTimeseries("root.liyb.test.name");
            //            IotDbSessionUtils.deleteTimeseries("root.liyb.test.age");
            //            IotDbSessionUtils.deleteTimeseries("root.liyb.test.work");

            // IotDbSessionUtils.deleteStorageGroup("root.liyb");

            //            IotDbSessionUtils.createTimeseries("root.liyb.test.name",
            //                    TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.SNAPPY);
            //
            //            IotDbSessionUtils.createTimeseries("root.liyb.test.age",
            //                    TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.SNAPPY);
            //            IotDbSessionUtils.createTimeseries("root.liyb.test.age",
            //                    TSDataType.INT32, TSEncoding.RLE, CompressionType.SNAPPY);

            //            IotDbSessionUtils.createTimeseries("root.liyb.test.work",
            //                    TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.SNAPPY);

            System.out.println(IotDbSessionUtils.checkTimeseriesExists("root.liyb.test"));

            //            insertRecord();

            SessionDataSetWrapper sessionDataSetWrapper =
                    IotDbSessionUtils.executeQueryStatement("select count(*) from root.liyb.test");
            System.out.println(sessionDataSetWrapper.getColumnNames());

            long x = 0;
            long y = 0;
            while (sessionDataSetWrapper.hasNext()) {
                RowRecord rowRecord = sessionDataSetWrapper.next();
                List<Field> fieldList = rowRecord.getFields();
                if (CollectionUtils.isNotEmpty(fieldList)) {
                    for (Field field : fieldList) {
                        y = field.getLongV();
                        if (x < y) {
                            x = y;
                        }
                    }
                }
                System.out.println("num=" + x);
            }

            // SessionDataSetWrapper sessionDataSetWrapper =
            //        IotDbSessionUtils.pool.executeQueryStatement("show timeseries root.liyb.test");
            // System.out.println(sessionDataSetWrapper.getColumnNames());
            //
            // while (sessionDataSetWrapper.hasNext()) {
            //    RowRecord rowRecord = sessionDataSetWrapper.next();
            //    List<Field> list = rowRecord.getFields();
            //    String field = list.get(0).toString();
            //    field = field.substring(field.lastIndexOf(".") + 1);
            //    System.out.println(field + "  " + list.get(3).toString());
            // }
            //
            // SessionDataSetWrapper sessionDataSetWrapper2 =
            //        IotDbSessionUtils.pool.executeQueryStatement("show devices");
            // System.out.println(sessionDataSetWrapper.getColumnNames());
            // while (sessionDataSetWrapper2.hasNext()) {
            //    RowRecord rowRecord = sessionDataSetWrapper2.next();
            //    List<Field> list = rowRecord.getFields();
            //    String field = list.get(0).toString();
            //    System.out.println(field);
            // }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void select() throws Exception {
        String sql = "select count(name) from root.liyb.stu";
        Connection conn = null;
        DruidDataSource druidDataSource = null;
        String url = "jdbc:iotdb://192.168.0.22:6667/";
        String user = "root";
        String pwd = "root";
        try {
            //            Class.forName("org.apache.iotdb.jdbc.IoTDBDriver");
            //            conn = DriverManager.getConnection(url, user, pwd);

            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setUrl(url);
            dataSource.setUsername(user);
            dataSource.setPassword(pwd);
            dataSource.setDriverClassName("org.apache.iotdb.jdbc.IoTDBDriver");

            // 配置初始化大小、最小、最大
            dataSource.setInitialSize(5);
            dataSource.setMinIdle(5);
            dataSource.setMaxActive(200);

            // 配置获取连接等待超时的时间
            dataSource.setMaxWait(30000);

            // 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
            dataSource.setTimeBetweenEvictionRunsMillis(60000);

            // 配置一个连接在池中最小生存的时间，单位是毫秒
            dataSource.setMinEvictableIdleTimeMillis(60000);
            dataSource.setTestWhileIdle(true);
            // dataSource.setValidationQuery("SELECT 1");
            dataSource.setTestOnBorrow(false);
            dataSource.setTestOnReturn(false);

            // 如果获取连接失败，则放弃获取直接跳出
            dataSource.setBreakAfterAcquireFailure(true);

            // 打开PSCache，并且指定每个连接上PSCache的大小
            dataSource.setPoolPreparedStatements(true);
            dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
            druidDataSource = dataSource;

            conn = druidDataSource.getConnection();

            PreparedStatement ps = null;
            ResultSet rs = null;
            ps = conn.prepareStatement("select count(name) from root.liyb.stu");
            ResultSet resultSet = ps.executeQuery();
            if (resultSet.next()) {
                long size = resultSet.getLong(1);
                System.out.println(size);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void insertRecord() throws Exception {
        long time = System.currentTimeMillis();
        List<String> measurements = new ArrayList<>();
        measurements.add("name");
        measurements.add("age");
        measurements.add("work");
        List<Object> values = new ArrayList<>();
        values.add("qq");
        values.add("10");
        values.add("student");
        List<TSDataType> types = new ArrayList<>();
        types.add(TSDataType.TEXT);
        types.add(TSDataType.TEXT);
        types.add(TSDataType.TEXT);
        IotDbSessionUtils.insertRecord(deviceId, time, measurements, types, values);
    }
}
